<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,Chrome=1" />
  <title>JSON localhost S/L</title>
</head>

<body>

  <div>
    <input id="files" type="file" /> <br />
    <input type="button" value="保存 obj" onclick="saveHandler(data_obj,'obj')" />
    <input type="button" value="保存 arr" onclick="saveHandler(data_arr,'arr')" />
    <input type="button" value="保存 str" onclick="saveHandler(data_str,'str')" />
    <input type="button" value="保存 num" onclick="saveHandler(data_num,'num')" />
    <input type="button" value="保存 bol" onclick="saveHandler(data_bol,'bol')" />
    <input type="button" value="保存 fun" onclick="saveHandler(data_fun,'fun')" />
    <input type="button" value="保存 nul" onclick="saveHandler(data_nul,'nul')" />
    <input type="button" value="保存 udf" onclick="saveHandler(data_udf,'udf')" />
  </div>

  <script src="./library/FileSaver.js"></script>
  <script>
    var inputElement = document.getElementById("files");
    inputElement.addEventListener("change", handleFiles, false);

    function handleFiles() {
      var selectedFile = document.getElementById("files").files[0]; //获取读取的File对象
      var name = selectedFile.name; //读取选中文件的文件名
      var size = selectedFile.size; //读取选中文件的大小
      console.log("文件名:" + name + "大小：" + size);
      var reader = new FileReader(); //这里是核心！！！读取操作就是由它完成的。
      reader.readAsText(selectedFile); //读取文件的内容

      reader.onload = function() {
        console.log("读取结果：", this.result); //当读取完成之后会回调这个函数，然后此时文件的内容存储到了result中。直接操作即可。

        console.log("读取结果转为JSON：");
        let json = JSON.parse(this.result);
        console.log(json);
      };
    }


    var data_obj = {
      name: "hanmeimei",
      age: 88
    }
    var data_arr = [{
      name: "hanmeimei",
      age: 88
    }, 1212, "1212211", true]
    var data_str = "???"
    var data_num = 88
    var data_bol = true;
    var data_fun = function() {
      console.log("this is a function");
    }
    var data_nul = null;
    var data_udf = undefined;

    function saveHandler(data, FileName) {
      if (!data || typeof data == 'function') {
        alert("无效数据！");
        return false;
      }
      if (!FileName) FileName = "save.json";
      if (FileName.indexOf(".json") == -1) FileName = FileName + ".json";

      var content = JSON.stringify(data);
      var blob = new Blob([content], {
        type: "text/plain;charset=utf-8"
      });
      saveAs(blob, FileName);
    }
  </script>

</body>

</html>